<template>
  <div class="gird-management">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>

        <el-form-item :label="$t('page.system.gird.status')">
          <el-select
            v-model="searchForm.status"
            :placeholder="$t('page.system.gird.status')"
            clearable
            style="width: 120px"
          >
            <el-option :label="$t('page.system.gird.available')" :value="1" />
            <el-option :label="$t('page.system.gird.unavailable')" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('page.system.gird.title')">
          <el-input
            v-model="searchForm.title"
            :placeholder="$t('page.system.gird.title')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.gird.userId')">
          <el-input-number
            v-model="searchForm.userId"
            :placeholder="$t('page.system.gird.userId')"
            style="width: 120px"
            :min="1"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.gird.userMembershipId')">
          <el-input-number
            v-model="searchForm.userMembershipId"
            :placeholder="$t('page.system.gird.userMembershipId')"
            style="width: 150px"
            :min="1"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            {{ $t('page.system.gird.search') }}
          </el-button>
          <el-button @click="handleReset">
            {{ $t('page.system.gird.reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        + {{ $t('page.system.gird.add') }}
      </el-button>
      <el-button
        type="danger"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete"
      >
        {{ $t('page.system.gird.batchDelete') }}
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="title" :label="$t('page.system.gird.title')" min-width="150">
        <template #default="scope">
          {{ scope.row.title ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="coverImageUrl" :label="$t('page.system.gird.coverImage')" width="120">
        <template #default="scope">
          <el-image
            v-if="scope.row.coverImageUrl"
            :src="scope.row.coverImageUrl"
            style="width: 80px; height: 60px"
            fit="cover"
            :preview-src-list="[scope.row.coverImageUrl]"
          />
          <span v-else class="text-gray-400">{{ $t('page.system.gird.noCover') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="$t('page.system.gird.status')" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? $t('page.system.gird.normal') : $t('page.system.gird.disabled') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="position" :label="$t('page.system.gird.position')" width="80">
        <template #default="scope">
          {{ scope.row.position ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="userId" :label="$t('page.system.gird.userId')" width="100">
        <template #default="scope">
          {{ scope.row.userId ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="userMembershipId" :label="$t('page.system.gird.userMembershipId')" width="120">
        <template #default="scope">
          {{ scope.row.userMembershipId ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="levelName" :label="$t('page.system.gird.levelName')" width="100">
        <template #default="scope">
          {{ scope.row.levelName ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="viewCount" :label="$t('page.system.gird.viewCount')" width="100">
        <template #default="scope">
          {{ scope.row.viewCount ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="expireTime" :label="$t('page.system.gird.expireTime')" width="180">
        <template #default="scope">
          {{ scope.row.expireTime ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="description" :label="$t('page.system.gird.description')" min-width="150" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.description ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" :label="$t('page.system.gird.createdTime')" width="180">
        <template #default="scope">
          {{ scope.row.createdTime ?? '-' }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('page.system.gird.operation')" width="150" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            {{ $t('page.system.gird.edit') }}
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">
            {{ $t('page.system.gird.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.pageNum"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <GirdForm
        ref="formRef"
        :form-data="currentRow"
        @submit="handleSubmit"
      />
      <template #footer>
        <el-button @click="dialogVisible = false">
          {{ $t('page.system.gird.cancel') }}
        </el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleConfirm">
          {{ $t('page.system.gird.confirm') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElImage,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElPagination,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';
import { $t } from '#/locales';

import GirdForm from './components/GirdForm.vue';
import { girdApi } from '../../../api/system/gird';

interface GirdRecord {
  id?: number;
  userId?: number;
  title: string;
  coverImage?: string;
  coverImageUrl?: string;
  description?: string;
  status: number;
  position?: number;
  userMembershipId: number;
  reminderSent?: boolean;
  viewCount?: number;
  levelId?: number;
  levelName?: string;
  expireTime?: string;
  gridWidth?: number;
  gridHeight?: number;
  createdTime?: string;
  updateTime?: string;
}

const tableRef = ref();
const formRef = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const submitLoading = ref(false);
const currentRow = ref<GirdRecord | null>(null);
const selectedRows = ref<GirdRecord[]>([]);
const tableData = ref<GirdRecord[]>([]);

// 搜索表单
const searchForm = reactive({
  title: '',
  status: undefined as number | undefined,
  userId: undefined as number | undefined,
  userMembershipId: undefined as number | undefined,
});

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const dialogTitle = computed(() => {
  return currentRow.value?.id 
    ? $t('page.system.gird.edit')
    : $t('page.system.gird.add');
});

// 获取数据
async function fetchData() {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...searchForm,
    };
    const response = await girdApi.getGirdPage(params);
    
    // 由于 requestClient 配置了 responseReturn: 'data'，response 直接是 data 部分
    const dataList = response.result || response.records || [];
    tableData.value = dataList;
    pagination.total = response.total;
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
}

// 搜索
function handleSearch() {
  pagination.pageNum = 1;
  fetchData();
}

// 重置搜索
function handleReset() {
  Object.assign(searchForm, {
    title: '',
    status: undefined,
    userId: undefined,
    userMembershipId: undefined,
  });
  pagination.pageNum = 1;
  fetchData();
}

// 新增
function handleAdd() {
  currentRow.value = null;
  dialogVisible.value = true;
}

// 编辑
function handleEdit(row: GirdRecord) {
  currentRow.value = { ...row };
  dialogVisible.value = true;
}

// 删除
function handleDelete(row: GirdRecord) {
  ElMessageBox.confirm(
    $t('page.system.gird.message.deleteConfirm'),
    '提示',
    {
      confirmButtonText: $t('page.system.gird.confirm'),
      cancelButtonText: $t('page.system.gird.cancel'),
      type: 'warning',
    }
  ).then(async () => {
    try {
      await girdApi.deleteGird(row.id!);
      ElMessage.success($t('page.system.gird.message.deleteSuccess'));
      fetchData();
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  });
}

// 批量删除
function handleBatchDelete() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }

  ElMessageBox.confirm(
    $t('page.system.gird.message.batchDeleteConfirm'),
    '提示',
    {
      confirmButtonText: $t('page.system.gird.confirm'),
      cancelButtonText: $t('page.system.gird.cancel'),
      type: 'warning',
    }
  ).then(async () => {
    try {
      const ids = selectedRows.value.map((row) => row.id!);
      await girdApi.batchDeleteGird(ids);
      ElMessage.success($t('page.system.gird.message.batchDeleteSuccess'));
      fetchData();
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  });
}

// 表格选择变化
function handleSelectionChange(selection: GirdRecord[]) {
  selectedRows.value = selection;
}

// 分页大小变化
function handleSizeChange(size: number) {
  pagination.pageSize = size;
  pagination.pageNum = 1;
  fetchData();
}

// 页码变化
function handleCurrentChange(page: number) {
  pagination.pageNum = page;
  fetchData();
}

// 弹窗确认
function handleConfirm() {
  formRef.value?.submit();
}

// 表单提交
async function handleSubmit(values: GirdRecord) {
  submitLoading.value = true;
  try {
    if (currentRow.value?.id) {
      // 编辑
      await girdApi.updateGird({ ...values, id: currentRow.value.id });
      ElMessage.success($t('page.system.gird.message.updateSuccess'));
    } else {
      // 新增
      await girdApi.createGird(values);
      ElMessage.success($t('page.system.gird.message.createSuccess'));
    }
    dialogVisible.value = false;
    fetchData();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  } finally {
    submitLoading.value = false;
  }
}

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.gird-management {
  padding: 20px;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 16px;
}

.toolbar .el-button {
  margin-right: 8px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
